import dayjs from "dayjs";
import { ref, onMounted, h } from "vue";
import { usePublicHooks } from "../hooks";
import { cloneDeep, isAllEmpty } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "../utils/types";
import elForm from '../form.vue'
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { DictTreeList, addDict, updateDict, delDict } from "@/utils/api/system/dict";

export function useDept() {
    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();

    const columns = ref<any>([
        {
            label: $t('Dict.dictName'),
            prop: "Name",
            width: 250,
            align: "left"
        },
        {
            label: $t('Dict.dictCode'),
            prop: "Code",
            minWidth: 150
        },
        {
            label: $t('Dict.dictValue'),
            prop: "Value",
            minWidth: 130
        },
        {
            label: $t('Dict.instructions'),
            prop: "Note",
            minWidth: 200
        },
        {
            label: $t('Dict.status'),
            prop: "Status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.Status)}>
                    {row.Status === 1 ? $t('Dict.enable') : $t('Dict.disable')}
                </el-tag>
            )
        },
        {
            label: $t('Dict.creationTime'),
            minWidth: 200,
            prop: "CreateTime",
            formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
        },
        {
            label: $t('Dict.operation'),
            fixed: "right",
            width: 160,
            slot: "operation"
        }
    ]);

    function tableReloading() {
        columns.value = [
            {
                label: $t('Dict.dictName'),
                prop: "Name",
                width: 250,
                align: "left"
            },
            {
                label: $t('Dict.dictCode'),
                prop: "Code",
                minWidth: 150
            },
            {
                label: $t('Dict.dictValue'),
                prop: "Value",
                minWidth: 130
            },
            {
                label: $t('Dict.instructions'),
                prop: "Note",
                minWidth: 200
            },
            {
                label: $t('Dict.status'),
                prop: "Status",
                minWidth: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.Status)}>
                        {row.Status === 1 ? $t('Dict.enable') : $t('Dict.disable')}
                    </el-tag>
                )
            },
            {
                label: $t('Dict.creationTime'),
                minWidth: 200,
                prop: "CreateTime",
                formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
            },
            {
                label: $t('Dict.operation'),
                fixed: "right",
                width: 160,
                slot: "operation"
            }
        ]
    }

    function formatOptions(treeList) {
        const menu = [{ Id: 1, Name: '主类目', Children: [] }];
        menu[0].Children = treeList
        // console.log(menu)
        return menu;
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        let newTitle = title === '新增' ? $t('Dict.addDictionary') : $t('Dict.editDictionary');
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    higherDeptOptions: formatOptions(cloneDeep(dataList.value)),
                    ParentId: row?.ParentId ?? 0,
                    Name: row?.Name ?? "",
                    Code: row?.Code ?? "",
                    Value: row?.Value ?? "",
                    Note: row?.Note ?? "",
                    Sort: row?.Sort ?? null,
                    Status: row?.Status ?? 1
                }
            },
            width: "40%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message(`您${title}了字典名称为${curData.Name}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            //@ts-ignore
                            addDict(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { Id: row.Id })
                            //@ts-ignore
                            updateDict(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    async function onSearch() {
        loading.value = true;
        const { Content } = await DictTreeList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
        let newData = Content;
        //@ts-ignore
        dataList.value = newData; // 处理成树结构
        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.Name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delDict(row.Id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了字典名称为${row.Name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    onMounted(() => {
        onSearch()
    })

    return {
        dataList,
        loading,
        columns,
        onSearch,
        openDialog,
        handleDelete,
        tableReloading
    };
}
